package com.hopedove.tempdemo.view

import android.graphics.Bitmap
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.GridLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.hopedove.tempdemo.utils.BitmapUtil
import com.orhanobut.logger.Logger

@BindingAdapter("bmp")
fun setImageViewBitmap(imageView: ImageView, base64: String?) {
    base64?.let {
        val bmp = BitmapUtil.fromBase64(base64)
        imageView.setImageBitmap(bmp)
    }
}


@BindingAdapter("mhListData")
fun setMHListData(textView: TextView, list: List<String>?) {
    list?.reduce { acc, s -> "${acc}\n$s" }?.let {
        textView.text = "麻灰: $it"
    }
}


@BindingAdapter("tshtListData")
fun setSpecialStripe(textView: TextView, list: List<String>?) {

    list?.map { it.replace("<br/>", "\n").replace("&nbsp;", " ") }?.reduce { acc, s ->
        "$acc\n$s"
    }.let { textView.text = it }
}


@BindingAdapter("gridCellFill")
fun setGridlayoutChildrenFill(view: View, isFill: Boolean) {
    if (isFill && view.parent is GridLayout) {
        val layoutParam = view.layoutParams as GridLayout.LayoutParams
        layoutParam.rowSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL)
    }
}

@BindingAdapter("jzblText")
fun setJzblText(container: FrameLayout, raw: String?) {
    val group = raw?.split("  ") ?: return
    if (group.size != 2) return
    container.removeAllViews()

    val leftTexts = group[0].split(":").reduce { acc, s -> "$acc\n$s" }
    val rightTexts = group[1].split(":").reduce { acc, s -> "$acc\n$s" }

    val context = container.context

    val lTextView = TextView(context).apply {
        text = leftTexts
        layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        ).apply { gravity = Gravity.START }
    }

    val rTextView = TextView(context).apply {
        text = rightTexts
        layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        ).apply { gravity = Gravity.END }
    }

    container.addView(lTextView)
    container.addView(rTextView)
}

@BindingAdapter("detailComment")
fun setDetailCommentContent(textView: TextView, comment: String?) {
    val content = comment?.replace("；", "；\n")?.replace("</br>", "\n")
    textView.text = content
}

@BindingAdapter("setQrCode")
fun setQrBitmap(imageView: ImageView, bitmap: Bitmap?) {
    Logger.d("setQrCode   $bitmap")
    bitmap?.let { bmp ->
        imageView.setImageBitmap(bmp)
    }
}

@BindingAdapter("setBitmap")
fun setBitmap(imageView: ImageView, bitmap: Bitmap?) {
    bitmap?.let { bmp ->
        imageView.setImageBitmap(bmp)
    }
}
